package com.study.rocketmq.consumer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * 消息接收者
 *
 * @author wanghuilong
 * @version 1.0
 * @date 2021/4/2 11:18 上午
 */
@Slf4j
public class Consumer {

    public static void main(String[] args) throws MQClientException {
        //1.创建消费者Consumer，制定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("c_group1");
        //2.指定Nameserver地址
        consumer.setNamesrvAddr("10.211.55.3:9876;10.211.55.4:9876");
        //3.订阅主题Topic和Tag
        //consumer.subscribe("TopicTest","TagA || TagB");
        consumer.subscribe("TopicTest", "*");
        //设定消费模式：广播模式/负载均衡模式,默认负载均衡
        consumer.setMessageModel(MessageModel.BROADCASTING);
        //4.设置回调函数，处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (int i = 0; i < msgs.size(); i++) {
                    MessageExt messageExt = msgs.get(i);
                    log.info("messageId:{} body:{}", messageExt.getMsgId(), new String(messageExt.getBody()));
                }

                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //5.启动消费者consumer
        consumer.start();
    }

}
